/**
 *
 */
package com.guchenbo.example.encoding;

/**
 * @author Cre.Gu
 */
public class Utf8Utils {

    /**
     * 用UTF-8编码方式实现unicode,返回十六进制表示
     *
     * @param c java中char类型的就是对应的unicode
     * @return String
     * @author Cre.Gu at 2016年2月3日
     */
    public static String utf84UnicodeHex(Character c) {
        return Integer.toHexString(Integer.parseInt(utf84Unicode(c), 2));
    }

    /**
     * 用UTF-8编码方式实现unicode,返回二进制表示
     *
     * @param c java中char类型的就是对应的unicode
     * @return String
     * @author Cre.Gu at 2016年2月3日
     */
    public static String utf84Unicode(Character c) {
        String unicodeBinary = Integer.toBinaryString((int) c);
        String utf8Placeholder = gainPlaceholder((long) c);

        char[] cs = unicodeBinary.toCharArray();
        char[] ds = utf8Placeholder.toCharArray();

        for (int j = cs.length; j > 0; j--) {
            char c2 = cs[j - 1];

            for (int k = ds.length; k > 0; k--) {
                char d = ds[k - 1];

                if (d == 'x') {
                    ds[k - 1] = c2;
                    break;
                } else
                    continue;
            }
        }

        for (int j = 0; j < ds.length; j++) {
            char d = ds[j];
            if (d == 'x') {
                ds[j] = '0';
            }
        }

        return String.valueOf(ds);
    }

    private static String gainPlaceholder(long c) {
        long l1 = Long.parseLong("007F", 16);
        long l2 = Long.parseLong("07FF", 16);
        long l3 = Long.parseLong("FFFF", 16);
        long l4 = Long.parseLong("10FFFF", 16);

        long unil = c;

        if (0 <= unil && unil <= l1) {
            return "0xxxxxxx";
        } else if (l1 < unil && unil <= l2) {
            return "110xxxxx10xxxxxx";
        } else if (l2 < unil && unil <= l3) {
            return "1110xxxx10xxxxxx10xxxxxx";
        } else if (l3 < unil && unil <= l4) {
            return "11110xxx10xxxxxx10xxxxxx10xxxxxx";
        } else
            throw new IllegalArgumentException("unicode编码未在支持范围内");

    }
}
